<template>
  <div class="point-storm-detail">
    <div class="header">
      <button class="header-button back" type="button" @click="handleBack">
        返回
      </button>
      <div class="title">点数风暴明细</div>
      <button class="header-button refresh" type="button" :disabled="loading" @click="refreshList">
        {{ loading ? '刷新中...' : '刷新列表' }}
      </button>
    </div>

    <div class="pager" v-if="totalPage > 0">
      <button class="pager-button" type="button" :disabled="loading || currentPage === 1" @click="goPrevPage">
        上一页
      </button>
      <div class="pager-info">
        第 {{ currentPage }} / {{ totalPage }} 页
      </div>
      <button
        class="pager-button"
        type="button"
        :disabled="loading || currentPage === totalPage"
        @click="goNextPage"
      >
        下一页
      </button>
    </div>

    <div class="content">
      <div v-if="errorMessage" class="state-message error">
        {{ errorMessage }}
      </div>
      <div v-else-if="loading && rounds.length === 0" class="state-message">
        数据加载中...
      </div>
      <div v-else-if="!loading && rounds.length === 0" class="state-message">
        暂无数据
      </div>

      <div v-for="round in rounds" :key="round.dice_id" class="round-card">
        <div class="round-card__header">
          <div class="round-card__index">第 {{ round.sequence }} 局</div>
          <div class="round-card__time">
            <div class="round-card__time-item">
              开始：{{ round.start_time || '—' }}
            </div>
            <div class="round-card__time-item">
              结束：{{ round.end_time || '—' }}
            </div>
          </div>
        </div>

        <div class="round-card__body">
          <div class="info-row">
            <span class="info-label">游戏时长</span>
            <span class="info-value">
              {{ round.gameTime ? `${round.gameTime} min` : '—' }}
            </span>
          </div>
          <div class="info-row">
            <span class="info-label">单次价格</span>
            <span class="info-value">
              {{ round.perPrice ? `${round.perPrice}` : '—' }}
            </span>
          </div>
          <div class="info-row">
            <span class="info-label">奖品信息</span>
            <span class="info-value prize-count">共 {{ round.prizeNum || 0 }} 个奖品</span>
          </div>
          <div class="prize-list">
            <div v-for="(prize, idx) in round.awardData" :key="`${round.dice_id}-${idx}`" class="prize-item">
              <div class="prize-thumb">
                <img v-if="prize.prizeImg" :src="prize.prizeImg" alt="奖品图片" @error="handlePrizeImgError($event)" />
                <div v-else class="thumb-placeholder">无图</div>
              </div>
              <div class="prize-name">{{ prize.prizeName || '-' }}</div>
            </div>
          </div>
        </div>

        <div class="round-card__footer">
          <button class="detail-button" type="button" @click="openDetail(round)">
            查看明细
          </button>
        </div>
      </div>

    </div>

    <div class="pager pager--bottom" v-if="totalPage > 0">
      <button class="pager-button" type="button" :disabled="loading || currentPage === 1" @click="goPrevPage">
        上一页
      </button>
      <div class="pager-info">
        第 {{ currentPage }} / {{ totalPage }} 页
      </div>
      <button
        class="pager-button"
        type="button"
        :disabled="loading || currentPage === totalPage"
        @click="goNextPage"
      >
        下一页
      </button>
    </div>

    <van-popup
      v-model="detailVisible"
      position="bottom"
      class="detail-popup"
      round
      :close-on-click-overlay="true"
      @click-overlay="closeDetail"
    >
      <div class="detail-popup__content">
        <div class="detail-popup__header">
          <div class="detail-popup__title">
            {{ activeRound ? `第 ${activeRound.sequence} 局明细` : '局明细' }}
          </div>
          <button class="popup-button" type="button" @click="refreshDetail" :disabled="detailLoading">
            {{ detailLoading ? '刷新中...' : '刷新明细' }}
          </button>
          <button class="popup-button close" type="button" @click="closeDetail">
            关闭
          </button>
        </div>

        <div v-if="detailError" class="detail-state-message error">
          {{ detailError }}
        </div>
        <div v-else-if="detailLoading && detailList.length === 0" class="detail-state-message">
          明细加载中...
        </div>
        <div v-else-if="!detailLoading && detailList.length === 0" class="detail-state-message">
          暂无明细数据
        </div>

        <div v-if="detailInfo" class="detail-summary">
          <div class="summary-item">
            <span class="summary-label">总投掷次数</span>
            <span class="summary-value">{{ detailInfo.size || 0 }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总消费金额</span>
            <span class="summary-value">{{ detailInfo.money || 0 }}</span>
          </div>
        </div>

        <div class="detail-pager" v-if="detailTotalPage > 0">
          <button
            class="popup-button"
            type="button"
            :disabled="detailLoading || detailCurrentPage === 1"
            @click="goDetailPrevPage"
          >
            上一页
          </button>
          <div class="detail-pager-info">
            第 {{ detailCurrentPage }} / {{ detailTotalPage }} 页
          </div>
          <button
            class="popup-button"
            type="button"
            :disabled="detailLoading || detailCurrentPage === detailTotalPage"
            @click="goDetailNextPage"
          >
            下一页
          </button>
        </div>

        <div class="detail-list">
          <div v-for="(player, index) in detailList" :key="player.detail_id || `${player.wx_name}-${index}`" class="player-card">
            <div class="player-order">#{{ (detailCurrentPage - 1) * detailPageSize + index + 1 }}</div>
            <div class="player-info">
              <div class="player-basic">
                <img :src="player.avatar" class="player-avatar" alt="头像" @error="handleAvatarError($event)" />
                <div class="player-name">{{ player.nickname || '-' }}</div>
              </div>
              <div class="player-stats">
                <div class="stat-item">
                  <span class="stat-label">投掷</span>
                  <span class="stat-value">{{ player.hby_size || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">最高点数</span>
                  <span class="stat-value">{{ player.c02 || '-' }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">金额</span>
                  <span class="stat-value">{{ player.gsum || 0 }}</span>
                </div>
              </div>
              <div class="player-time">{{ formatDateTime(player.create_time) }}</div>
            </div>
          </div>
        </div>

        <div class="detail-pager detail-pager--bottom" v-if="detailTotalPage > 0">
          <button
            class="popup-button"
            type="button"
            :disabled="detailLoading || detailCurrentPage === 1"
            @click="goDetailPrevPage"
          >
            上一页
          </button>
          <div class="detail-pager-info">
            第 {{ detailCurrentPage }} / {{ detailTotalPage }} 页
          </div>
          <button
            class="popup-button"
            type="button"
            :disabled="detailLoading || detailCurrentPage === detailTotalPage"
            @click="goDetailNextPage"
          >
            下一页
          </button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getPointStormRoundDetail, getPointStormRoundList } from '@/api/pointStorm';
import defaultAvatar from '@/assets/headImg.jpg';

function parsePointJson(pointJson) {
  if (!pointJson) return {};
  try {
    if (typeof pointJson === 'string') {
      return JSON.parse(pointJson);
    }
    return pointJson;
  } catch (error) {
    console.warn('点数风暴 pointJson 解析失败: ', error);
    return {};
  }
}

function normalizePlayer(item = {}) {
  return {
    nickname: item.wx_name || item.nickname || '-',
    avatar: item.avator || item.avatar || defaultAvatar,
    hby_size: item.hby_size,
    c02: item.c02,
    gsum: item.gsum,
    create_time: item.create_time,
    detail_id: item.detail_id,
  };
}

export default {
  name: 'PointStormDetail',
  data() {
    return {
      loading: false,
      rounds: [],
      currentPage: 1,
      pageSize: 5,
      totalResult: 0,
      totalPage: 0,
      errorMessage: '',

      detailVisible: false,
      activeRound: null,
      detailList: [],
      detailInfo: null,
      detailCurrentPage: 1,
      detailPageSize: 10,
      detailTotalPage: 0,
      detailLoading: false,
      detailError: '',
    };
  },
  created() {
    this.refreshList();
  },
  methods: {
    handleBack() {
      this.$emit('back-to-menu');
    },
    async refreshList() {
      this.currentPage = 1;
      this.rounds = [];
      await this.fetchRoundList({ showLoading: true });
    },
    async fetchRoundList({ showLoading = false } = {}) {
      if (showLoading) {
        this.loading = true;
        this.rounds = [];
      }
      this.errorMessage = '';
      try {
        const data = await getPointStormRoundList({
          currentPage: this.currentPage,
          showCount: this.pageSize,
        });
        this.totalResult = Number(data?.totalResult || 0);
        this.totalPage = Number(data?.totalPage || this.totalPage);
        const totalRounds = this.totalResult || 0;
        const list = (data?.list || []).map((item, index) => {
          const parsed = parsePointJson(item.pointJson);
          return {
            ...item,
            ...parsed,
            sequence: totalRounds - ((this.currentPage - 1) * this.pageSize + index),
            awardData: parsed.awardData || [],
          };
        });
        if (this.currentPage === 1) {
          this.rounds = list;
        } else {
          this.rounds = [...this.rounds, ...list];
        }
      } catch (error) {
        console.error('获取点数风暴列表失败: ', error);
        this.errorMessage = error.message || '列表加载失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    goPrevPage() {
      if (this.loading || this.currentPage <= 1) return;
      this.currentPage -= 1;
      this.fetchRoundList({ showLoading: true });
    },
    goNextPage() {
      if (this.loading || this.currentPage >= this.totalPage) return;
      this.currentPage += 1;
      this.fetchRoundList({ showLoading: true });
    },
    openDetail(round) {
      this.activeRound = round;
      this.detailVisible = true;
      this.detailCurrentPage = 1;
      this.detailList = [];
      this.detailInfo = null;
      this.fetchDetailList({ showLoading: true });
    },
    closeDetail() {
      this.detailVisible = false;
      this.activeRound = null;
      this.detailError = '';
      this.detailList = [];
      this.detailInfo = null;
    },
    async refreshDetail() {
      if (!this.activeRound) return;
      this.detailCurrentPage = 1;
      this.detailList = [];
      this.detailInfo = null;
      await this.fetchDetailList({ showLoading: true });
    },
    async fetchDetailList({ showLoading = false } = {}) {
      if (!this.activeRound) return;
      if (showLoading) {
        this.detailLoading = true;
      }
      this.detailError = '';
      try {
        const data = await getPointStormRoundDetail({
          diceId: this.activeRound.dice_id,
          currentPage: this.detailCurrentPage,
          showCount: this.detailPageSize,
        });
        const detailList = (data?.list || []).map((item) => normalizePlayer(item));
        this.detailInfo = data?.pointInfo || null;
        this.detailTotalPage = Number(data?.totalPage || 0);
        if (this.detailCurrentPage === 1) {
          this.detailList = detailList;
        } else {
          this.detailList = [...this.detailList, ...detailList];
        }
      } catch (error) {
        console.error('获取点数风暴明细失败: ', error);
        this.detailError = error.message || '明细加载失败，请稍后重试';
      } finally {
        this.detailLoading = false;
      }
    },
    goDetailPrevPage() {
      if (this.detailLoading || this.detailCurrentPage <= 1) return;
      this.detailCurrentPage -= 1;
      this.detailList = [];
      this.fetchDetailList({ showLoading: true });
    },
    goDetailNextPage() {
      if (this.detailLoading || this.detailCurrentPage >= this.detailTotalPage) return;
      this.detailCurrentPage += 1;
      this.detailList = [];
      this.fetchDetailList({ showLoading: true });
    },
    handlePrizeImgError(event) {
      if (event?.target) {
        event.target.style.display = 'none';
      }
    },
    handleAvatarError(event) {
      if (event?.target) {
        // eslint-disable-next-line no-param-reassign
        event.target.src = defaultAvatar;
      }
    },
    formatDateTime(value) {
      if (!value) return '-';
      const str = `${value}`.trim();
      let date;
      if (/^\d+$/.test(str)) {
        const timestamp = parseInt(str, 10);
        date = Number.isNaN(timestamp) ? null : new Date(timestamp);
      } else {
        const normalized = str.includes('T') ? str : str.replace(' ', 'T');
        date = new Date(normalized);
      }
      if (!date || Number.isNaN(date.getTime())) {
        return str;
      }
      const pad = (num) => String(num).padStart(2, '0');
      const year = date.getFullYear();
      const month = pad(date.getMonth() + 1);
      const day = pad(date.getDate());
      const hours = pad(date.getHours());
      const minutes = pad(date.getMinutes());
      const seconds = pad(date.getSeconds());
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    },
  },
};
</script>

<style scoped>
.point-storm-detail {
  min-height: 100vh;
  padding: 24px 20px 40px;
  box-sizing: border-box;
  color: #fff;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.pager {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 24px;
}

.pager--bottom {
  margin-top: 16px;
  margin-bottom: 0;
}

.pager-button {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: none;
  border-radius: 18px;
  padding: 8px 20px;
  font-size: 24px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.pager-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pager-info {
  font-size: 24px;
  color: rgba(255, 255, 255, 0.9);
}

.title {
  font-size: 32px;
  font-weight: 600;
}

.header-button {
  padding: 8px 16px;
  border-radius: 16px;
  border: none;
  font-size: 24px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.header-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.header-button.back {
  background: rgba(0, 0, 0, 0.2);
  color: #fff;
}

.header-button.refresh {
  background: #ffffff;
  color: #3e80f8;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.state-message {
  text-align: center;
  font-size: 26px;
  color: rgba(255, 255, 255, 0.85);
}

.state-message.error {
  color: #ffb6b6;
}

.round-card {
  background: rgba(255, 255, 255, 0.12);
  border-radius: 24px;
  padding: 20px 24px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

.round-card__header {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.round-card__index {
  font-size: 28px;
  font-weight: 600;
}

.round-card__time {
  font-size: 22px;
  line-height: 1.4;
  color: rgba(255, 255, 255, 0.8);
}

.round-card__time-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.round-card__body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 24px;
}

.info-label {
  color: rgba(255, 255, 255, 0.7);
}

.info-value {
  font-weight: 500;
}

.prize-count {
  font-size: 22px;
}

.prize-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 8px;
}

.prize-item {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 12px;
}

.prize-thumb {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
}

.prize-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumb-placeholder {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.6);
}

.prize-name {
  font-size: 22px;
  flex: 1;
  color: rgba(255, 255, 255, 0.95);
}

.round-card__footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.detail-button {
  background: #ffffff;
  color: #3e80f8;
  border: none;
  border-radius: 20px;
  padding: 10px 20px;
  font-size: 24px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.detail-button:active {
  opacity: 0.8;
}

.detail-popup {
  max-height: 80vh;
}

.detail-popup__content {
  padding: 24px 20px 36px;
  box-sizing: border-box;
}

.detail-popup__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.detail-popup__title {
  font-size: 30px;
  font-weight: 600;
  color: #333;
}

.popup-button {
  border: none;
  border-radius: 16px;
  padding: 8px 16px;
  font-size: 24px;
  cursor: pointer;
  background: #3e80f8;
  color: #fff;
  margin-left: 12px;
}

.popup-button.close {
  background: rgba(51, 51, 51, 0.1);
  color: #333;
}

.detail-state-message {
  text-align: center;
  font-size: 24px;
  color: #666;
  margin: 16px 0;
}

.detail-state-message.error {
  color: #f56c6c;
}

.detail-summary {
  display: flex;
  justify-content: space-between;
  background: #f4f8ff;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 16px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.summary-label {
  font-size: 22px;
  color: #666;
}

.summary-value {
  font-size: 26px;
  font-weight: 600;
  color: #3e80f8;
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.player-card {
  display: flex;
  gap: 12px;
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.player-order {
  font-size: 26px;
  font-weight: 600;
  color: #3e80f8;
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.player-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.player-basic {
  display: flex;
  align-items: center;
  gap: 12px;
}

.player-avatar {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  object-fit: cover;
}

.player-name {
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.player-stats {
  display: flex;
  gap: 16px;
  font-size: 22px;
  color: #555;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.stat-label {
  color: #888;
}

.stat-value {
  color: #333;
  font-weight: 500;
}

.player-time {
  font-size: 20px;
  color: #999;
}

.detail-pager {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin: 16px 0;
}

.detail-pager--bottom {
  margin-bottom: 0;
}

.detail-pager-info {
  font-size: 22px;
  color: #555;
}
</style>
